package com.juhuixing.feign.module.system.aspect;

import com.juhuixing.common.base.ResponseCode;
import com.juhuixing.common.base.ResponseData;
import com.juhuixing.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * 第三方接口异常统一封装处理
 * @author 刘猛
 * @date 2019/03/13
 */
@Aspect
@Component
@Slf4j
public class ThirdApiExceptionAspect {

    @Around("execution(* com.juhuixing.feign.module.system.service..*.*(..)) ")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        try {
            Object rs = pjp.proceed();
            if (rs instanceof ResponseData) {
                ResponseData rd = (ResponseData) rs;
                if (ResponseCode.SUCCESS_CODE.getCode() != rd.getCode()) {
                    MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
                    Method method = joinPointObject.getMethod();
                    log.info("异常调用的方法为={}", method.getName());
                    DefaultErrDesc errDesc = method.getAnnotation(DefaultErrDesc.class);
                    //获取方法上的注解当作异常信息
                    if (errDesc != null) {
                        throw new BusinessException(errDesc.code(), errDesc.msg(), new BusinessException(rd.getCode(), rd.getMessage()));
                    }
                }
            }
            return rs;
        } catch (Exception e) {
            MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
            Method method = joinPointObject.getMethod();
            DefaultErrDesc errDesc = method.getAnnotation(DefaultErrDesc.class);
            //获取方法上的注解当作异常信息
            if (errDesc != null) {
                throw new BusinessException(errDesc.code(), errDesc.msg(), e);
            } else {
                throw e;
            }
        }
    }

}
